package com.nextStep.service;

import com.nextStep.dao.UserMapper;
import com.nextStep.entity.SendEmailUser;
import com.nextStep.entity.Users;
import com.nextStep.utils.SendEmail;
import com.nextStep.utils.StringUtils;
import com.nextStep.utils.VeriCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service("userService")
public class UserServiceImpl implements UserService  {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserMapper userMapper;




    @Override
    public int updateUser(Users users) {
        return 0;
    }

    @Override
    public Users queryUser(Map map) {
        Users user = userMapper.queryUser(map);
        return user;
    }

    @Override
    public Integer equaleUser(Users users) {
        users.setPassword(users.getPassword() + "nextStepCompany");//md5 加盐
        users.setPassword(DigestUtils.md5DigestAsHex(users.getPassword().getBytes()));
        int retuNum;
        try {
            retuNum = userMapper.eqaleUser(users);
        } catch (Exception e) {
            logger.error("logFlag:" + e.getMessage(), e);
            return 0;
        }
        return retuNum;
    }

    @Override
    public Boolean sendUpdatePasswordVeriEmail(String userEmail, HttpServletRequest request ){
        VeriCode veriCode = VeriCode.getVeriCode();  //生成验证码对象
        String veriCodeStr = veriCode.veriCodeBuild();  //获取验证码
        userEmail=userEmail.split(":")[1].replaceAll("\"","").replaceAll("}","");   //获得键值对中的值
        request.getSession().setAttribute("updatePasswordVeriCode",veriCodeStr);  //保存验证码
        request.getSession().setAttribute("updatePasswordEmail",userEmail);  //保存修改密码邮箱
        SendEmailUser sendEmailUser = new SendEmailUser();
        sendEmailUser.setSendUserName("下一步科技");
        sendEmailUser.setTo(userEmail);
        sendEmailUser.setTheme("下一步科技---【修改密码】");
        sendEmailUser.setText("尊敬的用户：\n\n" +
                "    【下一步科技】您的登录验证码【"+veriCodeStr+"】\n\n"+
                "如非本人操作，请不要把验证码泄露给任何人。");
        SendEmail sendEmail = new SendEmail();

        boolean state = false;
        try {
            state = sendEmail.sendEmailTO(sendEmailUser);
        } catch (Exception e){
            logger.error("logFlag:"+e.getMessage(),e);
            return false;
        }

        return state;
    }

    @Override
    public Boolean updatePasswordVeriEnter(String veriEnter, HttpServletRequest request) {
        veriEnter = veriEnter.replace(" ", "");
        String veriCode = (String) request.getSession().getAttribute("updatePasswordVeriCode");
        veriEnter=veriEnter.split(":")[1].replaceAll("\"","").replaceAll("}","");   //获得键值对中的值

        if(veriEnter.equals(veriCode)){
            return true;
        }else{
            return  false;
        }
    }

    @Override
    public String addUser(Users users,String emailVeri,HttpServletRequest request) {
        Boolean state = selectUserExis(users); //查询该用户名或者邮箱是否存在
        if(StringUtils.isNull(users.getName()) ||StringUtils.isNull(users.getEmail())){
            state = false;
        }
        if(!emailVeri.equals(request.getSession().getAttribute("registerEmailVeriCode"))){
            state = false;  //验证码错误
        }
        if(state){  //不存在用户，可以注册
            users.setId( UUID.randomUUID().toString().replaceAll("-",""));   //生成id
            users.setPassword(users.getPassword()+"nextStepCompany");;  //md5 加盐
            users.setPassword(   DigestUtils.md5DigestAsHex(users.getPassword().getBytes())  );
            int stateCount = 0;
            try {
                stateCount = userMapper.addUser(users);
            } catch (Exception e) {
                logger.error("logFlag:"+e.getMessage(),e);
                return "";
            }
            if(stateCount == 1 ){
                return users.getId();   //成功
            }else {
                return "";   //其他错误
            }
        }else {   //存在用户名或者手机号相同的用户，拒绝注册
            return "";
        }
    }

    @Override
    public Boolean selectUserExis(Users user) {
        int stateCount = 0;
        try {
            stateCount = userMapper.selectUserExis(user);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return false;
        }


        if(stateCount == 0){
            return true;  //不存在用户
        }
        return false;   //已存在用户
    }

    @Override
    public Boolean updatePasswordEnter(String password,HttpServletRequest request) {
        String updatePasswordUserEmail = (String) request.getSession().getAttribute("updatePasswordEmail");   //获取修改密码用户的邮箱
        password=password.split(":")[1].replaceAll("\"","").replaceAll("}","");   //获得键值对中的值
        password+="nextStepCompany";  //md5 加盐
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        Map map = new HashMap();
        map.put("password",password);
        map.put("email",updatePasswordUserEmail);
        int stateCount = 0;
        try {
            stateCount = userMapper.updatePasswordEnter(map);
        } catch (Exception e){
            logger.error(e.getMessage(),e);
            return false;
        }
        if(stateCount == 1){
            return true;  //修改成功
        }
        return false;   //修改失败
    }

    @Override
    public boolean sendRegisterEmailVeri(String email, HttpServletRequest request) {
        String veriCodeStr = VeriCode.getVeriCode().veriCodeBuild();  //获取验证码
        email=email.split(":")[1].replaceAll("\"","").replaceAll("}","");   //获得键值对中的值
        //查询该邮箱是否曾注册过
        Users user = new Users();
        user.setEmail(email);
        int stateCount = userMapper.selectUserExis(user);
        if(stateCount!=0){ //该邮箱已存在，拒绝注册
            return false;
        }
        try{

            request.getSession().setAttribute("registerEmailVeriCode",veriCodeStr);  //保存验证码
            SendEmailUser sendEmailUser = new SendEmailUser();
            sendEmailUser.setSendUserName("下一步科技");
            sendEmailUser.setTo(email);
            sendEmailUser.setTheme("下一步科技---【注册】");
            sendEmailUser.setText("尊敬的用户：\n\n" +
                    "    【下一步科技】您的注册验证码【"+veriCodeStr+"】\n\n"+
                    "如非本人操作，请不要把验证码泄露给任何人。");
            SendEmail sendEmail = new SendEmail();
            boolean state = sendEmail.sendEmailTO(sendEmailUser);
            return state;

        }catch (Exception e){
            logger.error("logFlag:"+e.getMessage(),e);
            return false;
        }
    }

    @Override
    public void test() {
        System.out.println("test");
    }


}
